import axios from 'axios'
export default {
  // 开启命名空间
  namespaced: true,
  // 放数据的地方
  state: () => ({
    list: []
  }),
  // 相当于组件中计算属性
  getters: {
    total (state) {
      return state.list.reduce((sum, prev) => sum + prev.count, 0)
    },
    totalPrice (state) {
      return state.list.reduce((sum, prev) => sum + prev.count * prev.price, 0)
    }
  },
  // 这个是唯一修改state中数据地方
  mutations: {
    updateList (state, payload) {
      state.list = payload
    },
    updateCart (state, payload) {
      // 根据id找这个对象
      const obj = state.list.find(item => item.id === payload.id)
      obj.count = payload.count
    }
  },
  // 写异步的ajax的地方
  actions: {
    // store.commit()
    // getData(store){}
    async getCarts (context) {
      const res = await axios({
        url: 'http://localhost:3000/cart'
      })
      console.log(res)
      context.commit('updateList', res.data)
    },
    // 形参如果是对象可以解构
    async changeNum (context, payload) {
      console.log(payload)
      const res = await axios({
        method: 'PATCH',
        url: `http://localhost:3000/cart/${payload.id}`,
        data: {
          count: payload.count
        }
      })
      console.log(res)
      context.commit('updateCart', payload)
    }
  }
}
